<?php

header('Content-Type: text/html; charset=utf-8');

function SetDirAba($db,$TABLE, $SCRIPT)
{
     $ret = "<?php\n";
     $ret .= "echo \"<script type='text/javascript'>\\n\";\n";
     $ret .= "echo \"    \$(document).ready(function() {\\n\";\n";
     $sql = sprintf("SELECT aba FROM Page_mount WHERE Tabela='%s' AND script='%s' GROUP BY aba ORDER BY aba_order,aba,Linha,coluna", $TABLE, $SCRIPT);
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(PrepIncluir-2)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $n = 1;
               while($myrow = mysql_fetch_row($result))
               {
                    $myrow[0] = remover_acentos($myrow[0]);
                    $ret .= sprintf("echo \"            \$('#li-tabs-%02d').css({'display':'none'});\\n\";\n",$n);
                    $ret .= sprintf("if(isset(\$DIR_ABA_%s))\n",strtoupper(str_replace(" ","_",$TABLE)) . "_" . strtoupper(str_replace(" ","_",$myrow[0])));
                    $ret .= "{\n";
                    $ret .= sprintf("     echo \"            \$('#li-tabs-%02d').css({'display':'inline'});\\n\";\n",$n);
                    $ret .= "}\n";
                    $n++;
               }
          }
     }
     $sql = "SELECT aba FROM mount_link WHERE pagina='$TABLE' GROUP BY aba ORDER BY aba";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(PrepIncluir-2)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $myrow[0] = remover_acentos($myrow[0]);
                    $ret .= sprintf("echo \"            \$('#li-tabs-%02d').css({'display':'none'})\\n\";\n",$n,$n);
                    $ret .= sprintf("if(isset(\$DIR_ABA_%s))\n",strtoupper(str_replace(" ","_",$TABLE)) . "_" . strtoupper(str_replace(" ","_",$myrow[0])));
                    $ret .= "{\n";
                    $ret .= sprintf("     echo \"            \$('#li-tabs-%02d').css({'display':'inline'});\\n\";\n",$n,$n);
                    $ret .= "}\n";
                    $n++;
               }
          }
     }
     $ret .= "echo \"    });\\n\";\n";
     $ret .= "echo \"</script>\\n\";\n?>\n";
     return $ret;
}

function SetDir($db,$TABLE,$aba)
{
     $aba = remover_acentos($aba);
     $dir = "DIR_ABA_" . strtoupper(str_replace(" ","_",$TABLE)) . "_" . strtoupper(str_replace(" ","_",$aba));
     $comm1 = "Direitos da Aba " . $aba;
     $x = "ABA-" . $TABLE;
     $sql = "REPLACE INTO ListaDireitos VALUES('$dir','$comm1',NOW(),'$x')";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     $sql = "SELECT DISTINCT(idusuario) FROM Direitos ORDER BY idusuario";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(PrepIncluir-2)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $sql1 = "REPLACE INTO Direitos VALUES('$myrow[0]]','$dir',NOW())";
                    //printf("<p>$sql1</p>");
                    $result1 = mysql_query($sql1, $db);
                    if($result1 == 0)
                    {
                         printf("<h1>Falha: %s</h1>\n", mysql_error($db));
                         printf("<h3>%s</h3>\n", $sql1);
                         exit;
                    }
               }
          }
     }
}
function AvisoPHP()
{
     $out = '';
     $out .= "<div id='dialog-aviso' title='Aviso'>\n";
     $out .= "     <span style='float:left; margin:0 7px 20px 0;'></span><div id='aviso'></div>\n";
     $out .= "</div>\n";
     return $out;
}
function AvisoJS()
{
     $out = '';
     $out .= sprintf("<script type='text/javascript'>\n");
     $out .= sprintf("     var id_aviso = 0;\n");
     $out .= sprintf("     function Confirmar_Aviso(){\n");
     $out .= sprintf("          var url = 'confirm='+id_aviso;\n");
     $out .= sprintf("          $.getJSON('chkaviso_ajax.php',\n");
     $out .= sprintf("               url,\n");
     $out .= sprintf("               function(result){\n");
     $out .= sprintf("               }\n");
     $out .= sprintf("          )\n");
     $out .= sprintf("          .complete(function() {\n");
     $out .= sprintf("          })\n");
     $out .= sprintf("          .success(function() {\n");
     $out .= sprintf("          })\n");
     $out .= sprintf("          .error( function(jqXHR, textStatus, errorThrown) {\n");
     $out .= sprintf("               alert('error ' + textStatus);\n");
     $out .= sprintf("               alert('incoming Text ' + jqXHR.responseText);\n");
     $out .= sprintf("          });\n");
     $out .= sprintf("     }\n");
     $out .= sprintf("     function Adiar_Aviso(){\n");
     $out .= sprintf("          var url = 'adiar='+id_aviso;\n");
     $out .= sprintf("          $.getJSON('chkaviso_ajax.php',\n");
     $out .= sprintf("               url,\n");
     $out .= sprintf("               function(result){\n");
     $out .= sprintf("               }\n");
     $out .= sprintf("          )\n");
     $out .= sprintf("          .complete(function() {\n");
     $out .= sprintf("          })\n");
     $out .= sprintf("          .success(function() {\n");
     $out .= sprintf("          })\n");
     $out .= sprintf("          .error( function(jqXHR, textStatus, errorThrown) {\n");
     $out .= sprintf("               alert('error ' + textStatus);\n");
     $out .= sprintf("               alert('incoming Text ' + jqXHR.responseText);\n");
     $out .= sprintf("          });\n");
     $out .= sprintf("     }\n");
     $out .= sprintf("     (function($) {\n");
     $out .= sprintf("          $(document).ready(function(){\n");
     $out .= sprintf("               $(function() {\n");
     $out .= sprintf("                    setInterval( function () {\n");
     $out .= sprintf("                         $.ajax({\n");
     $out .= sprintf("                              url: 'chkaviso_ajax.php',\n");
     $out .= sprintf("                              dataType: 'json',\n");
     $out .= sprintf("                              success: function(data)\n");
     $out .= sprintf("                              {\n");
     $out .= sprintf("                                   var vAviso = 0;\n");
     $out .= sprintf("                                   for (var i = 0; i < data.length; i=i+3) {\n");
     $out .= sprintf("                                        if(data[i] == 'MESSENGER'){\n");
     $out .= sprintf("                                             var newwindow = window.open('messenger.php', 'large', 'width=1024, height=800, scrollbars=yes, location=no');\n");
     $out .= sprintf("                                             newwindow.restore();\n");
     $out .= sprintf("                                             newwindow.focus();\n");
     $out .= sprintf("                                             continue;\n");
     $out .= sprintf("                                        }\n");
     $out .= sprintf("                                        if(data[i] == 'AGENDA'){\n");
     $out .= sprintf("                                             var params = 'height='+screen.height+',width='+screen.width;\n");
     $out .= sprintf("                                             window.open('agenda/index.php','agenda',params);\n");
     $out .= sprintf("                                             continue;\n");
     $out .= sprintf("                                        }\n");
     $out .= sprintf("                                        id_aviso = data[i];\n");
     $out .= sprintf("                                        vAviso = data[i+2];\n");
     $out .= sprintf("                                        $('#dialog-aviso').dialog('option', 'title', 'AVISO DE: '+ vAviso);\n");
     $out .= sprintf("                                        $('#aviso').html('<h3>'+data[i+1]+'</h3>');\n");
     $out .= sprintf("                                        $('#dialog-aviso').dialog('open');\n");
     $out .= sprintf("                                   }\n");
     $out .= sprintf("                              }\n"); 
     $out .= sprintf("                         });\n");
     $out .= sprintf("                    }, 30000);\n");
     $out .= sprintf("                    $('#dialog-aviso').dialog({\n");
     $out .= sprintf("                         autoOpen: false,\n");
     $out .= sprintf("                         resizable: false,\n");
     $out .= sprintf("                         width: 500,\n");
     $out .= sprintf("                         height:300,\n");
     $out .= sprintf("                         modal: true,\n");
     $out .= sprintf("                         buttons: {\n");
     $out .= sprintf("                              'Manter': function() {\n");
     $out .= sprintf("                                   $( this ).dialog('close');\n");
     $out .= sprintf("                              },\n");
     $out .= sprintf("                              'Confirmar': function() {\n");
     $out .= sprintf("                                   Confirmar_Aviso();\n");
     $out .= sprintf("                                   $( this ).dialog('close');\n");
     $out .= sprintf("                              },\n");
     $out .= sprintf("                              'Adiar': function() {\n");
     $out .= sprintf("                                   Adiar_Aviso();\n");
     $out .= sprintf("                                   $(this).dialog('close');\n");
     $out .= sprintf("                              }\n");
     $out .= sprintf("                         },\n");
     $out .= sprintf("                         close: function() {\n");
     $out .= sprintf("                         }\n");
     $out .= sprintf("                    });\n");
     $out .= sprintf("               });\n");
     $out .= sprintf("          });\n");
     $out .= sprintf("     })(jQuery);\n");
     $out .= sprintf("</script>\n");
     return $out;
}

function prepSelect($db, $table, $script, &$ajax, &$tbl, &$wh, &$list)
{
     $ajax = "";
     $list = "";
     $chave = sprintf("id%s", strtolower($table));
     $sql = sprintf("SELECT campo,tipo FROM Page_mount WHERE Tabela='%s' AND script='%s' AND Lista > '0' ORDER BY aba_order,aba,Lista", $table, $script);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(PrepAjax-4)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $n = 0;
               $tbl = " FROM " . $table;
               $wh = " WHERE 1";
               $ajax .= "SELECT id$table as id,";
               while($myrow = mysql_fetch_row($result))
               {
                    if(substr(strtolower($myrow[0]), 0, 2) == "id")
                    {
                         $sel = ucfirst(substr($myrow[0], 2, strlen($myrow[0]) - 2));
                         if(strstr($sel, "_id") != "")
                         {
                              $tb2 = strstr($sel, "_id");
                              $sel = substr($sel, 0, strlen($sel) - strlen($tb2));
                         }

                         if(strstr($sel, "_") != "")
                         {
                              list($first, $second) = explode("_", $sel);
                              $sel = sprintf("%s_%s", ucfirst($first), ucfirst($second));
                         }
                         if(is_numeric(substr($sel, strlen($sel) - 1, 1)))
                         {
                              $sel = substr($sel, 0, strlen($sel) - 1);
                         }

                         if($sel != ucfirst($table))
                         {
                              $cp = GetCampo1($db, $myrow[0]);
                              if($list != '')
                              {
                                   $list .= ",";
                              }
                              $list .= sprintf("\$row[%s_%s]", strtolower($sel), strtolower($cp));
                              if($n == 0)
                              {
                                   $ajax .= sprintf("%s.%s as %s_%s", $sel, $cp, strtolower($sel), strtolower($cp));
                              }
                              else
                              {
                                   $ajax .= sprintf(",%s.%s as %s_%s", $sel, $cp, strtolower($sel), strtolower($cp));
                              }
                              //printf("<p>tbl: %s  $sel:$sel</p>");
                              $s = $sel . " ";
                              if(strstr($tbl, $s) == "")
                              {
                                   if($tbl == '')
                                   {
                                        $tbl .= " FROM $sel ";
                                   }
                                   else
                                   {
                                        $tbl .= ",$sel ";
                                   }
                              }
                              $s = sprintf("%s.id%s=", $sel, $sel);
                              if(strstr($wh, $s) == '')
                              {
                                   if($wh == '')
                                   {
                                        $wh .= sprintf("%s.id%s=%s.%s", $sel, $sel, $table, $myrow[0]);
                                   }
                                   else
                                   {
                                        $wh .= sprintf(" AND %s.id%s=%s.%s", $sel, $sel, $table, $myrow[0]);
                                   }
                              }
                              $n++;
                              continue;
                         }
                    }
                    if($myrow[1] == "mediumblob")
                    {
                         continue;
                    }
                    else if($myrow[1] == "date")
                    {
                         if($list != '')
                         {
                              $list .= ",";
                         }
                         $list .= sprintf("\$row[%s_%s]", strtolower($table), strtolower($myrow[0]));
                         if($n == 0)
                         {
                              $ajax .= sprintf("DATE_FORMAT(%s.%s,'%%d/%%m/%%Y') as %s_%s", $table, $myrow[0], strtolower($table), strtolower($myrow[0]));
                         }
                         else
                         {
                              $ajax .= sprintf(",DATE_FORMAT(%s.%s,'%%d/%%m/%%Y') as %s_%s", $table, $myrow[0], strtolower($table), strtolower($myrow[0]));
                         }
                    }
                    else if($myrow[1] == "datetime")
                    {
                         if($list != '')
                         {
                              $list .= ",";
                         }
                         $list .= sprintf("\$row[%s_%s]", strtolower($table), strtolower($myrow[0]));
                         if($n == 0)
                         {
                              $ajax .= sprintf("DATE_FORMAT(%s.%s,'%%d/%%m/%%Y %%H:%%i') as %s_%s", $table, $myrow[0], strtolower($table), strtolower($myrow[0]));
                         }
                         else
                         {
                              $ajax .= sprintf(",DATE_FORMAT(%s.%s,'%%d/%%m/%%Y %%H:%%i') as %s_%s", $table, $myrow[0], strtolower($table), strtolower($myrow[0]));
                         }
                    }
                    else
                    {
                         if($list != '')
                         {
                              $list .= ",";
                         }
                         $list .= sprintf("\$row[%s_%s]", strtolower($table), strtolower($myrow[0]));
                         if($n == 0)
                         {
                              $ajax .= $table . "." . $myrow[0] . " as " . strtolower($table) . "_" . strtolower($myrow[0]);
                         }
                         else
                         {
                              $ajax .= "," . $table . "." . $myrow[0] . " as " . strtolower($table) . "_" . strtolower($myrow[0]);
                         }
                    }
                    $n++;
               }
          }
     }
}

function prepColModel($db, $table, $script, &$names)
{
     $ajax = "";
     $list = "";
     $chave = sprintf("id%s", strtolower($table));
     $sql = sprintf("SELECT campo,tipo FROM Page_mount WHERE Tabela='%s' AND script='%s' AND Lista > '0' ORDER BY aba_order,aba,Lista", $table, $script);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(PrepAjax-4)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $n = 0;
               while($myrow = mysql_fetch_row($result))
               {
                    if($myrow[1] == "mediumblob")
                    {
                         continue;
                    }
                    if(substr(strtolower($myrow[0]), 0, 2) == "id")
                    {
                         $sel = ucfirst(substr($myrow[0], 2, strlen($myrow[0]) - 2));
                         if(strstr($sel, "_id") != "")
                         {
                              $tb2 = strstr($sel, "_id");
                              $sel = substr($sel, 0, strlen($sel) - strlen($tb2));
                         }

                         if(strstr($sel, "_") != "")
                         {
                              list($first, $second) = explode("_", $sel);
                              $sel = sprintf("%s_%s", ucfirst($first), ucfirst($second));
                         }
                         if(is_numeric(substr($sel, strlen($sel) - 1, 1)))
                         {
                              $sel = substr($sel, 0, strlen($sel) - 1);
                         }

                         if($sel != ucfirst($table))
                         {
                              $cp = GetCampo1($db, $myrow[0]);
                              if($list != '')
                              {
                                   $list .= ",";
                              }
                              $names[$n] = sprintf("%s.%s", $sel, $cp);
                         }
                    }
                    else
                    {
                         $names[$n] = sprintf("%s.%s", $table, $myrow[0]);
                    }
                    $n++;
               }
          }
     }
}

function Check_Link($db, $table, &$tabela, &$aba)
{
     $ret = "";
     $sql = "SELECT tabela,aba FROM mount_link WHERE pagina='$table'";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $tabela = $myrow[0];
                    $aba = $myrow[1];
               }
          }
     }
     return;
}

function Mount_Link_Aba($db, $table, $n)
{
     $ret = "";
     $sql = "SELECT aba FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $ret .= sprintf("                    <li id='li-tabs-%02d'><a href=\"#tabs-%02d\">%s</a></li>\n", $n + 1, $n + 1, $myrow[0]);
                    SetDir($db,$table,$myrow[0]);
                    $n++;
               }
          }
     }
     return $ret;
}

function Mount_Link($db, $table, $aba)
{
     $ret = "";
     $sql = "SELECT pagina,tabela FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {

                    $ret .= sprintf("                    <div id=\"tabs-%02d\">\n", $aba + 1);
                    $ret .= "                         <br/>\n";
                    $ret .= "                         <div align='left'>\n";
                    $ret .= "                               <table id='list_" . strtolower($myrow[0]) . "_" . strtolower($myrow[1]) . "'></table>\n";
                    $ret .= "                               <div id='pager_" . strtolower($myrow[0]) . "_" . strtolower($myrow[1]) . "'></div>\n";
                    $ret .= "                          </div>\n";
                    $ret .= "                          <br/>\n";
                    $ret .= "                    </div>\n";
                    $aba++;
               }
          }
     }
     return $ret;
}

function Mount_Link_Js($db, $table)
{
     $ret = "";
     $sql = "SELECT pagina,tabela FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $ret .= sprintf("<script type=\"text/javascript\" src=\"%s_%s.js\"></script>\n", strtolower($myrow[0]), strtolower($myrow[1]));
               }
          }
     }
     return $ret;
}

function Mount_Link_Js1($db, $table)
{
     $ret = "";
     $sql = "SELECT pagina,tabela FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $ret .= sprintf("          jQuery(\"#list_%s_%s\").trigger(\"reloadGrid\");\n", strtolower($myrow[0]), strtolower($myrow[1]));
               }
          }
     }
     return $ret;
}

function Mount_Link_Js2($db, $table)
{
     $ret = "";
     $sql = "SELECT pagina,tabela FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $ret .= sprintf("          jQuery(\"#pager_%s_%s\").block({ message: null });\n", strtolower($myrow[0]), strtolower($myrow[1]));
               }
          }
     }
     return $ret;
}

function Mount_Link_Js3($db, $table)
{
     $ret = "";
     $sql = "SELECT pagina,tabela FROM mount_link WHERE pagina='$table' GROUP BY aba order by aba";
     //printf("<p>%s</p>",$sql);
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $ret .= sprintf("          jQuery(\"#pager_%s_%s\").unblock();\n", strtolower($myrow[0]), strtolower($myrow[1]));
               }
          }
     }
     return $ret;
}

function CreateMontagem($dbctl)
{
     $sql = "DROP TABLE Page_mount";
     $result = mysql_query($sql, $dbctl);
     $sql = "CREATE TABLE `Page_mount` (";
     $sql .= "idmontagem INT(10) NOT NULL AUTO_INCREMENT COMMENT 'Chave primaria',";
     $sql .= "`tabela` VARCHAR(50) NOT NULL COMMENT 'Nome da Tabela' COLLATE 'utf8_general_ci',";
     $sql .= "`campo` VARCHAR(50) NOT NULL COMMENT 'Nome do Campo' COLLATE 'utf8_general_ci',";
     $sql .= "`tipo` VARCHAR(50) NOT NULL COMMENT 'Tipo do Campo' COLLATE 'utf8_general_ci',";
     $sql .= "`tamanho` varchar(50) NOT NULL COMMENT 'Tamanho do Campo',";
     $sql .= "`script` VARCHAR(32) NOT NULL COMMENT 'Script' COLLATE 'utf8_general_ci',";
     $sql .= "`aba` VARCHAR(50) NOT NULL COMMENT 'Nome na Aba' COLLATE 'utf8_general_ci',";
     $sql .= "`aba_order` SMALLINT(5) NOT NULL DEFAULT '1' COMMENT 'Posicao da aba',";
     $sql .= "`label` VARCHAR(32) NOT NULL COMMENT 'Titulo do Campo' COLLATE 'utf8_general_ci',";
     $sql .= "`linha` SMALLINT(5) NOT NULL COMMENT 'Posicao na Edicao',";
     $sql .= "`coluna` SMALLINT(5) NOT NULL COMMENT 'Coluna',";
     $sql .= "`lista` SMALLINT(6) NOT NULL COMMENT 'Posicao na Lista',";
     $sql .= "`popup` VARCHAR(32) NOT NULL COMMENT 'Campo para PopUp' COLLATE 'utf8_general_ci',";
     $sql .= "`pesquisa` SMALLINT(6) NOT NULL COMMENT 'Pesquisa ou Select',";
     $sql .= "`fixar` VARCHAR(255) NOT NULL COMMENT 'Valor a FIXAR' COLLATE 'utf8_general_ci',";
     $sql .= "`where` VARCHAR(255) NOT NULL COMMENT 'Clausula WHERE' COLLATE 'utf8_general_ci',";
     $sql .= "PRIMARY KEY (`idmontagem`),";
     $sql .= "UNIQUE INDEX `UK_Montagem` (`tabela`, `script`, `campo`)";
     $sql .= ")";
     $sql .= "COMMENT='Montagem do Formulario' ";
     $sql .= "CHARACTER SET utf8 COLLATE='utf8_general_ci' ";
     $sql .= "ENGINE=MyISAM";
     $result = mysql_query($sql, $dbctl);
     if($result == 0)
     {
          printf("<h1>(function-1)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }

     $sql = "CREATE TABLE `Menu_mount` (";
     $sql .= "`idmenu` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Chave primaria',";
     $sql .= "`menu` VARCHAR(64) NOT NULL COMMENT 'Nome do Menu' COLLATE 'utf8_general_ci',";
     $sql .= "`titulo` VARCHAR(64) NOT NULL COMMENT 'Titulo do Menu' COLLATE 'utf8_general_ci',";
     $sql .= "`url` VARCHAR(64) NOT NULL COMMENT 'Url' COLLATE 'utf8_general_ci',";
     $sql .= "`Automatico` TINYINT(4) NOT NULL DEFAULT '1' COMMENT 'Automatico',";
     $sql .= "`tabela` VARCHAR(64) NOT NULL COMMENT 'Tabela' COLLATE 'utf8_general_ci',";
     $sql .= "PRIMARY KEY (`idmenu`),";
     $sql .= "UNIQUE INDEX `UK_Menu` (`servidor`, `db`, `menu`, `titulo`)";
     $sql .= ")";
     $sql .= "COMMENT='Montagem do Menu'";
     $sql .= "COLLATE='utf8_general_ci'";
     $sql .= "ENGINE=MyISAM";
     $result = mysql_query($sql, $dbctl);
}

function getTableInfo($dbctl, $Server, $Login, $Senha, $Database, $Table)
{
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     mysql_select_db($Database, $dbDIR);
     $sql = "DELETE FROM Page_mount WHERE tabela='$Table'";
     $result = mysql_query($sql, $dbctl);
     $sql = "SHOW FULL COLUMNS FROM $Table";
     $result = mysql_query($sql, $dbDIR);
     if($result == 0)
     {
          printf("<h1>(function-1)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $itens = 8;
               if(isset($_REQUEST['ITENS']))
               {
                    $itens = $_REQUEST['ITENS'];
               }
               $ntab = 1;
               $count = 0;
               $linha = 0;
               $lista = 0;
               $n = 0;
               while($myrow = mysql_fetch_row($result))
               {
                    $npg = 0;
                    if($n == 0)
                    {
                         $nch = 0;
                         if(strstr($myrow[8], "|") != "")
                         {
                              $CH = explode("|", $myrow[8]);
                              $m = 0;
                              while(isset($CH[$m]))
                              {
                                   if(strlen($CH[$m]) > 0)
                                   {
                                        $nch++;
                                   }
                                   $m++;
                              }
                         }
                         else
                         {
                              $CH[0] = $myrow[8];
                              $nch++;
                         }
                         for($m = 0; $m < $nch; $m++)
                         {
                              //printf("<p>CH:%s</p>",$CH[$m]);
                              //list($titulo, $linha, $coluna, $aba, $lista, $menu) = explode(";", $CH[$m]);
                              //list($menu,$titulo) = explode(";", $CH[$m]);
                              $marr = explode(";", $CH[$m]);
                              //printf("<p>0->$marr[0] - 1->$marr[1] - 2->$marr[2]</p>");
                              if($marr[2] != "")
                              {
                                   $TIT[$m] = $marr[2];
                              }
                              else
                              {
                                   $TIT[$m] = $marr[1];
                              }
                              $titulo = $marr[1];
                              $menu = $marr[0];
                              //$url = sprintf("Cad%s.php", $titulo);
                              //printf("<p>menu:%s</p>",$menu);
                              //printf("<p>titulo:%s</p>",$titulo);
                              //printf("<p>url:%s</p>",$url);
                              //$titulo = sprintf("%s", ucfirst($Table));
                              $url = sprintf("Cad%s.php", ucfirst($Table));
                              $sql1 = "REPLACE INTO Menu_mount VALUES('0','$menu','$titulo','$url','1','$Table')";
                              $result1 = mysql_query($sql1, $dbctl);
                              if($result1 == 0)
                              {
                                   printf("<h1>(function-2)Falha: %s</h1>\n", mysql_error($dbctl));
                                   printf("<h3>%s</h3>\n", $sql1);
                                   exit;
                              }
                         }
                         $n++;
                         continue;
                    }
                    list($tipo, $size) = explode(";", getSize($myrow[1]));
                    if($tipo == "enum")
                    {
                         $size = mysql_real_escape_string($size);
                    }
                    if(strstr($myrow[8], ";") != "")
                    {
                         if(strstr($myrow[8], "|") != "")
                         {
                              $PG = explode("|", $myrow[8]);
                              $m = 0;
                              while(isset($PG[$m]))
                              {
                                   if(strlen($PG[$m]) > 0)
                                   {
                                        //printf("<p>PG%d:%s</p>", $m, $PG[$m]);
                                        $npg++;
                                   }
                                   $m++;
                              }
                         }
                         else
                         {
                              $PG[0] = $myrow[8];
                              $npg++;
                         }
                         //list($titulo, $linha, $coluna, $aba, $lista) = explode(";", $PG[0]);
                         $pop = "";
                         $pesq = "";
                         $fix = "";
                         $where = "";
                         $RES = explode(";", $PG[0]);
                         if(isset($RES[0]))
                         {
                              $titulo = $RES[0];
                         }
                         if(isset($RES[1]))
                         {
                              $linha = $RES[1];
                         }
                         if(isset($RES[2]))
                         {
                              $coluna = $RES[2];
                         }
                         if(isset($RES[3]))
                         {
                              $RES_ABA = explode("?", $RES[3]);
                              $aba = $RES_ABA[0];
                              $aba_res = '1';
                              if(isset($RES_ABA[1]))
                              {
                                   $aba_res = $RES_ABA[1];
                              }
                         }
                         if(isset($RES[4]))
                         {
                              $lista = $RES[4];
                         }
                         if(isset($RES[5]))
                         {
                              $pop = $RES[5];
                         }
                         if(isset($RES[6]))
                         {
                              $pesq = $RES[6];
                         }
                         if(isset($RES[7]))
                         {
                              $fix = $RES[7];
                         }
                         if(isset($RES[8]))
                         {
                              $where = $RES[8];
                         }
                    }
                    else
                    {
                         $chave = sprintf("id%s", strtolower($Table));
                         if($chave == strtolower($myrow[0]))
                         {
                              $sql1 = "REPLACE INTO Page_mount VALUES('0','$Table','$myrow[0]','int','11','$npg','','1','$chave','0','0','0','','','','')";
                              $sql1 = mysql_real_escape_string($sql1);
                              $result1 = mysql_query($sql1, $dbctl);
                              if($result1 == 0)
                              {
                                   printf("<h1>(function-3)Falha: %s</h1>\n", mysql_error($dbctl));
                                   printf("<h3>%s</h3>\n", $sql1);
                                   exit;
                              }
                              continue;
                         }
                         $titulo = $myrow[0];
                         $aba = sprintf("Tab-%02d", $count / $itens + 1);
                         $aba_order = '1';
                         $linha++;
                         $coluna = 1;
                         $lista++;
                         $count++;
                    }
                    if($npg == 0)
                    {
                         $where = str_replace("'", "''", $where);
                         $sql1 = "REPLACE INTO Page_mount VALUES('0','$Table','$myrow[0]','$tipo','$size','$TIT[0]','$aba','$aba_order','$titulo','$linha','$coluna','$lista','$pop','$pesq','$fix','$where')";
                         $result1 = mysql_query($sql1, $dbctl);
                         if($result1 == 0)
                         {
                              printf("<h1>(function-4)Falha: %s</h1>\n", mysql_error($dbctl));
                              printf("<h3>%s</h3>\n", $sql1);
                              exit;
                         }
                    }
                    else
                    {
                         for($m = 0; $m < $npg; $m++)
                         {
                              //list($titulo, $linha, $coluna, $aba, $lista) = explode(";", $PG[$m]);
                              $pop = "";
                              $pesq = "";
                              $fix = "";
                              $where = "";
                              $RES = explode(";", $PG[0]);
                              if(isset($RES[0]))
                              {
                                   $titulo = $RES[0];
                              }
                              if(isset($RES[1]))
                              {
                                   $linha = $RES[1];
                              }
                              if(isset($RES[2]))
                              {
                                   $coluna = $RES[2];
                              }
                              if(isset($RES[3]))
                              {
                                   $RES_ABA = explode("?", $RES[3]);
                                   $aba = $RES_ABA[0];
                                   $aba_res = '1';
                                   if(isset($RES_ABA[1]))
                                   {
                                        $aba_res = $RES_ABA[1];
                                   }
                              }
                              if(isset($RES[4]))
                              {
                                   $lista = $RES[4];
                              }
                              if(isset($RES[5]))
                              {
                                   $pop = $RES[5];
                              }
                              if(isset($RES[6]))
                              {
                                   $pesq = $RES[6];
                              }
                              if(isset($RES[7]))
                              {
                                   $fix = $RES[7];
                              }
                              if(isset($RES[8]))
                              {
                                   $where = $RES[8];
                              }
                              if(!isset($TIT[$m]))
                              {
                                   $TIT[$m] = $TIT[0] . $m;
                              }
                              $where = str_replace("'", "''", $where);
                              $sql1 = "REPLACE INTO Page_mount VALUES('0','$Table','$myrow[0]','$tipo','$size','$TIT[$m]','$aba','$aba_res','$titulo','$linha','$coluna','$lista','$pop','$pesq','$fix','$where')";
                              $result1 = mysql_query($sql1, $dbctl);
                              if($result1 == 0)
                              {
                                   printf("<h1>(function-5)Falha: %s</h1>\n", mysql_error($dbctl));
                                   printf("<h3>%s</h3>\n", $sql1);
                                   exit;
                              }
                         }
                    }
               }
          }
     }
     //mysql_close($dbctl);
     return;
}

function GetCampo1($db, $campo)
{
     $sel = substr($campo, 2, strlen($campo) - 2);
     if(strstr($sel, "_id") != "")
     {
          $tb2 = strstr($sel, "_id");
          $sel = substr($sel, 0, strlen($sel) - strlen($tb2));
     }
     if(is_numeric(substr($sel, strlen($sel) - 1, 1)))
     {
          $sel = substr($sel, 0, strlen($sel) - 1);
     }
     $tabela = ucfirst($sel);
     if(strstr($tabela, "_") != "")
     {
          list($first, $second) = explode("_", $tabela);
          $tabela = sprintf("%s_%s", ucfirst($first), ucfirst($second));
     }
     $sql = "SHOW COLUMNS FROM $tabela";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6a)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          $n = 0;
          while($myrow = mysql_fetch_row($result))
          {
               if($n == 1)
               {
                    $ret = $myrow[0];
                    break;
               }
               $n++;
          }
     }
     return $ret;
}

function GetCampo2($db, $tabela, &$campo0, &$campo1)
{
     $sql = "SHOW COLUMNS FROM $tabela";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6a)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          $n = 0;
          while($myrow = mysql_fetch_row($result))
          {
               if($n == 1)
               {
                    $campo0 = $myrow[0];
               }
               if($n == 2)
               {
                    $campo1 = $myrow[0];
                    break;
               }
               $n++;
          }
     }
     return;
}

function getIFMENU($db, $menu)
{
     $if = "";
     $sql = "SELECT titulo FROM Menu_mount WHERE menu='" . $menu . "' ORDER BY titulo";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-6)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $if = "<?php if(";
               $n = 0;
               $menuX = remover_acentos($menu);
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[0], 'button') != "")
                    {
                         continue;
                    }

                    $myrow[0] = str_replace(',', '_', $myrow[0]);
                    $d = remover_acentos($myrow[0]);
                    if($n == 0)
                    {
                         $if .= sprintf("isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", $menuX, $d, $menuX, $d);
                         //printf("isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", $menuX, $d, $menuX, $d);
                    }
                    else
                    {
                         $if .= sprintf(" || isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_LISTAR)", $menuX, $d, $menuX, $d);
                         //printf(" || isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_LISTAR)", $menuX, $d, $menuX, $d);
                    }
                    $n++;
               }
               $if .= ") { ?>\n";
          }
     }
     return $if;
}

function GetDir($db, $tabela)
{
     $ret = "";
     $sql = "SELECT menu,titulo FROM Menu_mount WHERE tabela='$tabela' ORDER BY menu,titulo";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-7)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[1], 'button') != "")
                    {
                         continue;
                    }
                    if(strstr($myrow[1], ',') != "")
                    {
                         $titulo = str_replace(',', '_', $myrow[1]);
                         //list($titulo, $sub) = explode(",", $myrow[1]);
                    }
                    else
                    {
                         $titulo = $myrow[1];
                    }
                    if($titulo == '')
                    {
                         $titulo = $myrow[0];
                    }
                    $titulo = remover_acentos($titulo);
                    $menu = remover_acentos($myrow[0]);
                    $ret .= sprintf("if(!isset(\$DIR_%s_%s_EDITAR) && !isset(\$DIR_%s_%s_LISTAR))\n", strtoupper($menu), strtoupper($titulo), strtoupper($menu), strtoupper($titulo));
               }
          }
     }
     return $ret;
}

function GetDirEdit($db, $tabela)
{
     $ret = "";
     $sql = "SELECT menu,titulo FROM Menu_mount WHERE tabela='$tabela' ORDER BY menu,titulo";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-7)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[1], 'button') != "")
                    {
                         continue;
                    }
                    if(strstr($myrow[1], ',') != "")
                    {
                         $titulo = str_replace(',', '_', $myrow[1]);
                         $sub = "";
                         //list($titulo, $sub) = explode(",", $myrow[1]);
                    }
                    else
                    {
                         $titulo = $myrow[1];
                    }
                    if($titulo == '')
                    {
                         $titulo = $myrow[0];
                    }
                    $titulo = remover_acentos($titulo);
                    $menu = remover_acentos($myrow[0]);
                    $ret .= sprintf("<?php if(isset(\$DIR_%s_%s_EDITAR)) { ?>\n", strtoupper($menu), strtoupper($titulo));
               }
          }
     }
     return $ret;
}

function GetDirList($db, $tabela)
{
     $ret = "";
     $sql = "SELECT menu,titulo FROM Menu_mount WHERE tabela='$tabela' ORDER BY menu,titulo";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-7)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[1], 'button') != "")
                    {
                         continue;
                    }
                    if(strstr($myrow[1], ',') != "")
                    {
                         //list($titulo, $sub) = explode(",", $myrow[1]);
                         $titulo = str_replace(',', '_', $myrow[1]);
                         //$sub = "";
                    }
                    else
                    {
                         $titulo = $myrow[1];
                    }
                    if($titulo == '')
                    {
                         $titulo = $myrow[0];
                    }
                    $titulo = remover_acentos($titulo);
                    $menu = remover_acentos($myrow[0]);
                    $ret .= sprintf("<?php if(isset(\$DIR_%s_%s_LISTAR)) { ?>\n", strtoupper($menu), strtoupper($titulo));
               }
          }
     }
     return $ret;
}

function GeraMenu($dbctl, $db, $diretorio, $nTables, &$TABLES, $dir)
{
     $menu = "          <ul class=\"menu\" id=\"menu\">\n";
     if($dir == "1")
     {
          $menu .= "          <?php\n";
          $menu .= "          if(";
          //mysql_select_db("rotondano", $dbctl);
          $sql = "SELECT menu,titulo,url FROM Menu_mount ORDER BY menu,titulo";
          $result = mysql_query($sql, $dbctl);
          if($result == 0)
          {
               printf("<h1>(function-7)Falha: %s</h1>\n", mysql_error($dbctl));
               printf("<h3>%s</h3>\n", $sql);
               exit;
          }
          else
          {
               if(mysql_num_rows($result) > 0)
               {
                    $n = 0;
                    while($myrow = mysql_fetch_row($result))
                    {
                         if(strstr($myrow[0], 'button') != "")
                         {
                              continue;
                         }
                         if(strstr($myrow[1], ',') != "")
                         {
                              //list($titulo, $sub) = explode(",", $myrow[1]);
                              $titulo = str_replace(',', '_', $myrow[1]);
                         }
                         else
                         {
                              $titulo = $myrow[1];
                         }
                         if($titulo == '')
                         {
                              $titulo = $myrow[0];
                         }
                         //printf("<p>$titulo</p>");
                         $titulo = remover_acentos($titulo);
                         $menuX = remover_acentos($myrow[0]);
                         //printf("<p>$titulo</p>");
                         if($n == 0)
                         {
                              $menu .= sprintf("isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", strtoupper($menuX), strtoupper($titulo), strtoupper($menuX), strtoupper($titulo));
                         }
                         else
                         {
                              $menu .= sprintf(" || isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", strtoupper($menuX), strtoupper($titulo), strtoupper($menuX), strtoupper($titulo));
                         }
                         $n++;
                    }
               }
          }
          $menu .= ")\n";
          $menu .= "          {\n";
          $menu .= "          ?>\n";
     }

     //mysql_select_db("rotondano", $dbctl);
     $sql = "SELECT menu,titulo,url FROM Menu_mount ORDER BY menu,titulo";
     $result = mysql_query($sql, $dbctl);
     if($result == 0)
     {
          printf("<h1>(function-7)Falha: %s</h1>\n", mysql_error($dbctl));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $mp = "";
               $sub = "";
               $titulo1 = "";
               $titulo = "";
               $pri = 0;
               $fim = "";
               while($myrow = mysql_fetch_row($result))
               {
                    if($myrow[1] == "")
                    {
                         list($url, $js) = explode(";", $myrow[2]);
                         list($a, $name) = explode("=", $js);
                         $js = "onclick=\"return popup(this, '$name')\"";
                         $fim .= sprintf("                              <li><a href='%s' %s class=\"menulink\">%s</a></li>\n", $url, $js, $myrow[0]);
                         continue;
                    }
                    if(strstr($myrow[0], "button|") != "")
                    {
                         continue;
                    }
                    if(strstr($myrow[1], ',') != "")
                    {
                         $titulox = str_replace(",", "_", $myrow[1]);
                         //$sub = "";
                         list($titulo, $sub) = explode(",", $myrow[1]);
                    }
                    else
                    {
                         $titulo = $myrow[1];
                         $titulox = $myrow[1];
                         $sub = "";
                    }
                    if($titulo == '')
                    {
                         $titulo = $myrow[0];
                    }
                    if($titulo != $titulo1)
                    {
                         $titulo1 = $titulo;
                         if($pri == 1)
                         {
                              $menu .= "                    </ul></li>\n";
                         }
                         $pri = 0;
                    }
                    if($mp != $myrow[0])
                    {
                         if($mp != "")
                         {
                              $menu .= "                    </ul>\n";
                              $menu .= "               </li>\n";
                              if($if != "")
                              {
                                   $menu .= "            <?php } ?>\n";
                              }
                         }
                         $if = getIFMENU($dbctl, $myrow[0]);
                         if($if != "")
                         {
                              $menu .= "               " . $if;
                         }
                         $menu .= "               <li><a href=\"#\" class=\"menulink\">$myrow[0]</a>\n";
                         $menu .= "                    <ul>\n";
                         $mp = $myrow[0];
                    }
                    if($dir == "1")
                    {
                         $d = remover_acentos($titulox);
                         $menuX = remover_acentos($myrow[0]);
                         Inserir_Dir($db, $d, $myrow[0], $menuX);
                         $menu .= sprintf("                    <?php if(isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)) { ?>\n", $menuX, $d, $menuX, $d);
                         //printf("                    if(isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)) { \n", $menuX, $d, $menuX, $d);
                    }
                    if(strstr($myrow[2], ";") == "")
                    {
                         $url = $myrow[2];
                         $js = "";
                    }
                    else
                    {
                         list($url, $js) = explode(";", $myrow[2]);
                         list($a, $name) = explode("=", $js);
                         //printf("<p>$myrow[2] ($url-$js)</p>");
                         //printf("<p>$a-$name)</p>");
                         $js = "onclick=\"return popup(this, '$name')\"";
                         //printf("<p>%s - %s - %s</p>",$myrow[2],$url,$js);
                    }
                    if($sub == "")
                    {
                         $menu .= sprintf("                              <li><a href='%s' %s>%s</a></li>\n", $url, $js, $titulo);
                    }
                    else
                    {
                         if($pri == 0)
                         {
                              $pri = 1;
                              $menu .= sprintf("                              <li><a href='%s' class='sub' %s>%s</a><ul>\n", $url, $js, $titulo);
                              $menu .= sprintf("                              <li class='topline'><a href='%s' %s>%s</a></li>\n", $url, $js, $sub);
                         }
                         else
                         {
                              $menu .= sprintf("                              <li><a href='%s' %s>%s</a></li>\n", $url, $js, $sub);
                         }
                    }
                    if($dir == "1")
                    {
                         $menu .= "                    <?php } ?>\n";
                    }
               }
          }
          $menu .= "                    </ul>\n";
          $menu .= "               </li>\n";
          if($if != "")
          {
               $menu .= "            <?php } ?>\n";
          }
          if($dir == "1")
          {
               $menu .= "          <?php } ?>\n";
          }
     }

     $menu .= "               <?php if(is_file(\"includes/index_Menu.inc.php\"))\n";
     $menu .= "               {\n";
     $menu .= "                    include 'includes/index_Menu.inc.php';\n";
     $menu .= "               }?>\n";
     $menu .= $fim;
     $menu .= "               <li><a href=\"login.php?Logout=1\" class=\"menulink\">Sair</a></li>\n";
     $menu .= "          </ul>\n";

     //Nome do Arquivo PHP
     $FILE = sprintf("%s/includes", $diretorio);
     if(!file_exists($FILE))
     {
          mkdir($FILE);
     }

     $FILE = sprintf("%s/includes/Menu.inc.php", $diretorio);
     $fPHP = fopen($FILE, "w");
     if(!$fPHP)
     {
          echo "<h1>Falha na Criacao do Arquivo '" . $FILE . "'</h1>";
          exit;
     }
     fprintf($fPHP, "%s", $menu);
     fclose($fPHP);
}

/*
  function GeraMenuOld($diretorio, $nTables, &$TABLES, $dir)
  {
  $menu = "          <ul class=\"menu\" id=\"menu\">\n";
  if($dir == "1")
  {
  $menu .= "          <?php\n";
  $menu .= "          if(";
  for($n = 0; $n < $nTables; $n++)
  {
  if($n == 0)
  {
  $menu .= sprintf("isset(\$DIR_%s_EDITAR) || isset(\$DIR_%s_LISTAR)", strtoupper($TABLES[$n]), strtoupper($TABLES[$n]));
  }
  else
  {
  $menu .= sprintf(" || isset(\$DIR_%s_EDITAR) || isset(\$DIR_%s_LISTAR)", strtoupper($TABLES[$n]), strtoupper($TABLES[$n]));
  }
  }
  $menu .= ")\n";
  $menu .= "          {\n";
  $menu .= "          ?>\n";
  }
  $menu .= "               <li><a href=\"#\" class=\"menulink\">Cadastros</a>\n";
  $menu .= "                    <ul>\n";
  for($n = 0; $n < $nTables; $n++)
  {
  if($dir == "1")
  {
  $menu .= sprintf("                    <?php if(isset(\$DIR_%s_EDITAR) || isset(\$DIR_%s_LISTAR)) { ?>\n", strtoupper($TABLES[$n]), strtoupper($TABLES[$n]));
  }
  $menu .= sprintf("                              <li><a href='Cad%s.php'>%s</a></li>\n", ucfirst($TABLES[$n]), ucfirst($TABLES[$n]));
  if($dir == "1")
  {
  $menu .= "                    <?php } ?>\n";
  }
  }
  if($dir == "1")
  {
  $menu .= "          <?php } ?>\n";
  }
  $menu .= "                    </ul>\n";
  $menu .= "               </li>\n";
  $menu .= "               <?php if(is_file(\"includes/index_Menu.inc.php\"))\n";
  $menu .= "               {\n";
  $menu .= "                    include 'includes/index_Menu.inc.php';\n";
  $menu .= "               }?>\n";
  $menu .= "               <li><a href=\"login.php?Troca=1\" class=\"menulink\">Troca Senha</a></li>\n";
  $menu .= "               <li><a href=\"login.php?Logout=1\" class=\"menulink\">Sair</a></li>\n";
  $menu .= "               <li><a href=\"#\" class=\"menulink\">&nbsp;<font color='#20FF20'><? echo \$_SESSION['USER']; ?> </font>&nbsp;</a></li>\n";
  $menu .= "          </ul>\n";

  //Nome do Arquivo PHP
  $FILE = sprintf("%s/includes", $diretorio);
  if(!file_exists($FILE))
  {
  mkdir($FILE);
  }

  $FILE = sprintf("%s/includes/Menu.inc.php", $diretorio);
  $fPHP = fopen($FILE, "w");
  if(!$fPHP)
  {
  echo "<h1>Falha na Criacao do Arquivo '" . $FILE . "'</h1>";
  exit;
  }
  fprintf($fPHP, "%s", $menu);
  fclose($fPHP);
  }
 */

function GeraIndex($dbctl, $db, $diretorio, $nTables, &$TABLES, $dir)
{
     $idmenu = 1;
     if($_REQUEST['Menu'] == 'Novo')
     {
          $idmenu = 0;
     }
     else if($_REQUEST['Menu'] == 'Potato')
     {
          $idmenu = 3;
     }
     else if($_REQUEST['Menu'] == 'Maujor')
     {
          $idmenu = 4;
     }
     $out = "<?php\n";
     $out .= "session_start();\n";
     //$out .= "require \"func.inc.php\";\n";
     if($dir == "1")
     {
          $out .= "require \"define.php\";\n";
          $out .= "if(!isset(\$_SESSION['USER']))\n";
          $out .= "{\n";
          $out .= "     Header(\"Location: login.php\");\n";
          $out .= "     exit();\n";
          $out .= "}\n";
     }
     if(isset($_REQUEST['CHAT']))
     {
          $out .= "\$_SESSION['username'] = \$_SESSION['USER'];\n";
     }
//     $out .= "include \"Functions.inc.php\";\n";
     $out .= "?>\n";
     $out .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
     $out .= "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='pt-br' lang='pt-br' >\n";
     $out .= "     <head>\n";
     $out .= "          <title>" . $_REQUEST['Title'] . " - Administrativo</title>\n";
     if(isset($_REQUEST['ISO']))
     {
          $out .= "          <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\n";
     }
     else if(isset($_REQUEST['UTF8']))
     {
          $out .= "          <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n";
     }
     $out .= "          <link type='text/css' href='<?php echo \$TEMA;?>' rel='stylesheet' />\n";
     if($idmenu == 0)
     {
          $out .= "          <link rel=\"stylesheet\" href=\"css/menu.css\" type=\"text/css\" />\n";
          $out .= "          <script type=\"text/javascript\" src=\"js/menu.js\"></script>\n";
     }
     else if($idmenu == 1)
     {
          $out .= "          <link href='css/menu1.css' rel='stylesheet' type='text/css' />\n";
     }
     else if($idmenu == 2)
     {
          $out .= "          <link rel=\"stylesheet\" href=\"css/fg.menu.css\" type=\"text/css\" />\n";
          $out .= "          <script type=\"text/javascript\" src=\"js/fg.menu.js\"></script>\n";
     }
     else if($idmenu == 4)
     {
          $out .= "          <script type='text/javascript' src='js/maujor.js'></script>\n";
          $out .= "          <link type='text/css' href='css/maujor.css' media='screen' rel='stylesheet' />\n";
     }
     $out .= "          <script type=\"text/javascript\" src=\"js/alert.js\"></script>\n";
     $out .= "          <script type=\"text/javascript\" src=\"js/jquery-1.6.4.min.js\"></script>\n";
     $out .= "          <script type=\"text/javascript\" src=\"js/jquery-ui-1.8.16.custom.min.js\"></script>\n";
     if($idmenu == 3)
     {
          $out .= "          <link rel=\"stylesheet\" href=\"css/jquery.ui.potato.menu.css\" type=\"text/css\" />\n";
          $out .= "          <script type=\"text/javascript\" src=\"js/jquery.ui.potato.menu.js\"></script>\n";
          $out .= "          <script type='text/javascript'>\n";
          $out .= "               (function($) {\n";
          $out .= "                    $(document).ready(function(){\n";
          $out .= "                         $('#potato').ptMenu();\n";
          $out .= "                    });\n";
          $out .= "          })(jQuery);\n";
          $out .= "          </script>\n";
     }
     if(isset($_REQUEST['Aviso']))
     {
          $out .= AvisoJS();
     }
     if(isset($_REQUEST['CHAT']))
     {
          $out .= "          <link type=\"text/css\" rel=\"stylesheet\" media=\"all\" href=\"css/chat.css\" />\n";
          $out .= "          <link type=\"text/css\" rel=\"stylesheet\" media=\"all\" href=\"css/screen.css\" />\n";
          $out .= "          <!--[if lte IE 7]>\n";
          $out .= "          <link type=\"text/css\" rel=\"stylesheet\" media=\"all\" href=\"css/screen_ie.css\" />\n";
          $out .= "          <![endif]-->\n";
          $out .= "          <script type='text/javascript'>\n";
          $out .= "               (function($) {\n";
          $out .= "                    $(document).ready(function(){\n";
          $out .= "                         setInterval( function () {\n";
          $out .= "                              $.ajax({\n";
          $out .= "                                   url: 'chkchat_ajax.php',\n";
          $out .= "                                   dataType: 'json',\n";
          $out .= "                                   success: function(data)\n";
          $out .= "                                   {\n";
          $out .= "                                        var val_li = \"<font size='1'>\";\n";
          $out .= "                                        for (var i = 0; i < data.length; i=i+3) {\n";
          $out .= "                                             if(data[i+2] == 1){\n";
          $out .= "                                                  val_li += \"<li><a href=\\\"javascript:void(0)\\\" onclick=\\\"javascript:chatWith('\"+data[i]+\"')\\\">\"+data[i+1]+\"</a></li>\";\n";
          $out .= "                                             }\n";
          $out .= "                                        }\n";
          $out .= "                                        val_li += \"</font>\";\n";
          $out .= "                                        $('#chat_users').html(val_li);\n";
          $out .= "                                   }\n"; 
          $out .= "                              });\n";
          $out .= "                         }, 10000);\n";
          $out .= "                         });\n";
          $out .= "               })(jQuery);\n";
          $out .= "          </script>\n";
     }

     $out .= "          <style type=\"text/css\">\n";
     $out .= "               body{ font: 70% \"Trebuchet MS\", sans-serif; margin: 5px;}\n";
     if(isset($_REQUEST['LOGOTIPO']))
     {
          $out .= "               html{ width: 100%; height: 100%;background:url(img/logo.png) center center no-repeat;}\n";
     }
     $out .= "          </style>\n";
     $out .= "     </head>\n";
     $out .= "     <body>\n";
     $out .= "<?php include 'includes/Menu.inc.php';?>\n";
     if(isset($_REQUEST['CHAT']))
     {
          $out .= "<div id=\"main_container\">\n";
          $out .= "<p id='chat_users'></p>\n";
          $out .= "</div>\n";
     }
     if($idmenu == 0)
     {
          $out .= "          <script type=\"text/javascript\">\n";
          $out .= "               var menu=new menu.dd(\"menu\");\n";
          $out .= "               menu.init(\"menu\",\"menuhover\");\n";
          $out .= "          </script>\n";
     }
     if(isset($_REQUEST['Aviso']))
     {
          $out .= AvisoPHP();
     }
     if(isset($_REQUEST['CHAT']))
     {
          $out .= "<script type=\"text/javascript\" src=\"js/chat.js\"></script>\n";
     }
     $out .= "          </body>\n";
     $out .= "          </html>\n";
     //Nome do Arquivo PHP
     $FILE = sprintf("%s/index.php", $diretorio);
     $fPHP = fopen($FILE, "w");
     if(!$fPHP)
     {
          echo "<h1>Falha na Criacao do Arquivo '" . $FILE . "'</h1>";
          exit;
     }
     fprintf($fPHP, "%s", $out);
     fclose($fPHP);

     //GeraMenu($dbctl, $db, $diretorio, $nTables, $TABLES, $dir);
     MontaMenu($dbctl, $diretorio, $idmenu);

     printf("<h3 align='center'> 'index.php' Gerado com Sucesso</h3>\n");
}

function getTables($Server, $Login, $Senha, $Database, &$Tables, &$Titulos)
{
     $ntables = 0;
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     mysql_select_db($Database, $dbDIR);
     $sql = "SHOW TABLE STATUS WHERE Comment LIKE 'Cadastro%'";
     $result = mysql_query($sql, $dbDIR);
     if($result == 0)
     {
          printf("<h1>(function-8)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    $Tables[$ntables] = $myrow[0];
                    $Titulos[$ntables] = trim(str_replace('LINK ','',$myrow[17]));
                    $ntables++;
               }
          }
     }
     return $ntables;
}

function CreateLink($dbctl)
{
     $sql = "DELETE FROM mount_link WHERE auto='1'";
     $result = mysql_query($sql, $dbctl);
     $sql = "CREATE TABLE IF NOT EXISTS `mount_link` (";
     $sql .= "idlink INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Chave primaria',";
     $sql .= "`pagina` VARCHAR(50) NOT NULL COMMENT 'Pagina na qual sera ligada' COLLATE 'utf8_general_ci',";
     $sql .= "`aba` VARCHAR(50) NOT NULL COMMENT 'Nome da aba' COLLATE 'utf8_general_ci',";
     $sql .= "`tabela` VARCHAR(50) NOT NULL COMMENT 'nome da tabela a ser utilizada' COLLATE 'utf8_general_ci',";
     $sql .= "`label` VARCHAR(50) NOT NULL COMMENT 'Nome do campo',";
     $sql .= "`campo` VARCHAR(50) NOT NULL COMMENT 'campo' COLLATE 'utf8_general_ci',";
     $sql .= "`posicao` SMALLINT(3) NOT NULL COMMENT 'Posicao',";
     $sql .= "`tipo` VARCHAR(16) NOT NULL COMMENT 'Tipo' COLLATE 'utf8_general_ci',";
     $sql .= "`tamanho` VARCHAR(16) NOT NULL COMMENT 'Tamanho' COLLATE 'utf8_general_ci',";
     $sql .= "`auto` TINYINT(1) NOT NULL COMMENT 'Automatico',";
     $sql .= "PRIMARY KEY (`idlink`),";
     $sql .= "UNIQUE INDEX `UK_link` (`pagina`, `tabela`, `campo`)";
     $sql .= ")";
     $sql .= "COMMENT='Montagem da tabela de Ligação' ";
     $sql .= "COLLATE='utf8_general_ci' ";
     $sql .= "ENGINE=MyISAM";
     $result = mysql_query($sql, $dbctl);
     if($result == 0)
     {
          printf("<h1>(function-1)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
}

function getLinkInfo($Server, $Login, $Senha, $Database, $Table)
{
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     mysql_select_db($Database, $dbDIR);
     $sql = "SHOW FULL COLUMNS FROM $Table";
     //printf("<p>%s</p>\n", $sql);
     $result = mysql_query($sql, $dbDIR);
     if($result == 0)
     {
          printf("<h1>(function-1)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $n = 0;
               $npags = 0;
               while($myrow = mysql_fetch_row($result))
               {
                    //printf("<p>%s</p>\n", $myrow[0]);
                    list($tipo, $tamanho) = explode(";", getSize($myrow[1]));
                    if($tipo == "enum")
                    {
                         $tamanho = mysql_real_escape_string($tamanho);
                    }
                    if($n == 0)
                    {
                         if(strstr($myrow[8],"|"))
                         {
                              $pr = explode("|", $myrow[8]);
                              for($m=0;$m<count($pr);$m++)
                              {
                                   $ar = explode(";", $pr[$m]);
                                   $pag[$m] = $ar[0];
                                   $aba[$m] = $ar[1];
                                   $npags++;
                              }
                         }
                         else
                         {
                              $ar = explode(";", $myrow[8]);
                              $pag[0] = $ar[0];
                              $aba[0] = $ar[1];
                              $npags = 1;
                         }
                         $n++;
                         continue;
                    }
                    if(strstr($myrow[8],"|"))
                    {
                         $pr = explode("|", $myrow[8]);
                         for($m=0;$m<count($pr);$m++)
                         {
                              $ar = explode(";", $pr[$m]);
                              if(strlen($ar[0]) > 0)
                              {
                                   //printf("<p>Label:%s  Pos: %s</p>\n", $ar[0], $ar[1]);
                                   $sql1 = "INSERT INTO mount_link VALUES('0','$pag[$m]','$aba[$m]','$Table','$ar[0]','$myrow[0]','$ar[1]','$tipo','$tamanho','1')";
                                   //printf("<p>%s</p>\n", $sql1);
                                   $result1 = mysql_query($sql1, $dbDIR);
                                   if($result1 == 0)
                                   {
                                        printf("<h1>(function-4)Falha: %s</h1>\n", mysql_error($dbDIR));
                                        printf("<h3>%s</h3>\n", $sql1);
                                        exit;
                                   }
                              }
                         }
                    }
                    else
                    {
                         $ar = explode(";", $myrow[8]);
                         if(strlen($ar[0]) > 0)
                         {
                              //printf("<p>Label:%s  Pos: %s</p>\n", $ar[0], $ar[1]);
                              $sql1 = "INSERT INTO mount_link VALUES('0','$pag[0]','$aba[0]','$Table','$ar[0]','$myrow[0]','$ar[1]','$tipo','$tamanho','1')";
                              //printf("<p>%s</p>\n", $sql1);
                              $result1 = mysql_query($sql1, $dbDIR);
                              if($result1 == 0)
                              {
                                   printf("<h1>(function-4)Falha: %s</h1>\n", mysql_error($dbDIR));
                                   printf("<h3>%s</h3>\n", $sql1);
                                   exit;
                              }
                         }
                    }
               }
          }
     }
     //mysql_close($dbctl);
     return;
}

function mountLink($Server, $Login, $Senha, $Database)
{
     $ntables = 0;
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     CreateLink($dbDIR);
     mysql_select_db($Database, $dbDIR);
     $sql = "SHOW TABLE STATUS WHERE Comment LIKE '%LINK %'";
     $result = mysql_query($sql, $dbDIR);
     if($result == 0)
     {
          printf("<h1>(function-8)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    getLinkInfo($Server, $Login, $Senha, $Database, $myrow[0]);
                    printf("<h3 align='center'>Ligação da Tabela '$myrow[0]' criada com Sucesso</h3>\n");
               }
          }
     }
     return;
}

function get2col($Server, $Login, $Senha, $Database, $sel)
{
     $ret = "???";
     if(strstr($sel, "_") != "")
     {
          list($first, $second) = explode("_", $sel);
          $sel = sprintf("%s_%s", ucfirst($first), ucfirst($second));
     }
     if(is_numeric(substr($sel, strlen($sel) - 1, 1)))
     {
          $sel = substr($sel, 0, strlen($sel) - 1);
     }
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     mysql_select_db($Database, $dbDIR);
     $sql = "SHOW COLUMNS FROM $sel";
     $result = mysql_query($sql, $dbDIR);
     if($result == 0)
     {
          printf("<h1>(function-9)Falha: %s</h1>\n", mysql_error($dbDIR));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $n = 0;
               while($myrow = mysql_fetch_row($result))
               {
                    $ret = $myrow[0];
                    if($n == 1)
                    {
                         break;
                    }
                    $n++;
               }
          }
     }
     return $ret;
}

function checkEnum($db, $Table, $Field)
{
     $sql = "SHOW FULL COLUMNS FROM $Table WHERE Field='$Field'";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>(function-10)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               while($myrow = mysql_fetch_row($result))
               {
                    list($resto, $tmp1) = explode("(", $myrow[1]);
                    list($tmp, $resto) = explode(")", $tmp1);
                    $ct = 0;
                    $r = strtok($tmp, ",");
                    while($r !== false)
                    {
                         $ct++;
                         if($r == "'F'" || $r == "'T'" || $r == "'V'" || $r == "'F'" || $r == "'S'" || $r == "'N'")
                         {
                              
                         }
                         else
                         {
                              return 0;
                         }
                         $r = strtok(",");
                    }
               }
               if($ct == 2)
               {
                    return 1;
               }
          }
     }
}

function setEnum($Server, $Login, $Senha, $Database, $Table, $campo, $ndx)
{
     $out = "";
     $dbDIR = mysql_connect($Server, $Login, $Senha);
     if(!$dbDIR)
     {
          printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
          exit;
     }
     mysql_select_db($Database, $dbDIR);
     $ret = checkEnum($dbDIR, $Table, $campo);
     if($ret == 1)
     {
          $out .= sprintf("<input type='checkbox' name='%s' id='%s' tabindex='%d'/>", strtoupper($campo), strtoupper($campo), $ndx);
     }
     else
     {
          $sql = "SHOW FULL COLUMNS FROM $Table WHERE Field='$campo'";
          $result = mysql_query($sql, $dbDIR);
          if($result == 0)
          {
               printf("<h1>(function-11)Falha: %s</h1>\n", mysql_error($dbDIR));
               printf("<h3>%s</h3>\n", $sql);
               exit;
          }
          else
          {
               if(mysql_num_rows($result) > 0)
               {
                    $out .= sprintf("<select name='%s' id='%s' tabindex='%d'>", strtoupper($campo), strtoupper($campo), $ndx);
                    while($myrow = mysql_fetch_row($result))
                    {
                         list($resto, $tmp1) = explode("(", $myrow[1]);
                         list($tmp, $resto) = explode(")", $tmp1);
                         $r = strtok($tmp, ",");
                         $r = str_replace("'", "", $r);
                         $out .= "<option value='" . $r . "'>" . $r . "</option>";
                         while($r != "")
                         {
                              $r = strtok(",");
                              if($r == "")
                              {
                                   break;
                              }
                              $r = str_replace("'", "", $r);
                              $out .= "<option value='" . $r . "'>" . $r . "</option>";
                         }
                    }
                    $out .= "</select>";
               }
          }
     }
     return $out;
}

/*
  function Inserir_Direitos($Server, $Login, $Senha, $Database, $Table)
  {
  $dbDIR = mysql_connect($Server, $Login, $Senha);
  if(!$dbDIR)
  {
  printf("<h1 align=center>Falha no conexao com a Base de Dados</h1>\n");
  exit;
  }
  mysql_select_db($Database, $dbDIR);

  $sql = "CREATE TABLE ListaDireitos (
  Direito VARCHAR(64) NOT NULL,
  Descricao VARCHAR(255) NOT NULL,
  data DATETIME NOT NULL,
  menu VARCHAR(64) NOT NULL,
  PRIMARY KEY (Direito)
  )";
  $result = mysql_query($sql, $dbDIR);

  $sql = "CREATE TABLE Direitos (
  idUsuario INT(11) NOT NULL AUTO_INCREMENT,
  Direito VARCHAR(64) NOT NULL,
  Data DATETIME NOT NULL,
  PRIMARY KEY (`idUsuario`, `Direito`)
  )
  COMMENT='Controle Direitos dos Usuarios'
  ENGINE=MyISAM";
  $result = mysql_query($sql, $dbDIR);


  $dir1 = "DIR_LISTAR_" . strtoupper($Table);
  $dir2 = "DIR_EDITAR_" . strtoupper($Table);
  $comm1 = "Listar Direitos da Tabela " . $Table;
  $comm2 = "Editar Direitos da Tabela " . $Table;
  $sql = "REPLACE INTO ListaDireitos VALUES('$dir1','$comm1',NOW())";
  $result = mysql_query($sql, $dbDIR);
  $sql = "REPLACE INTO ListaDireitos VALUES('$dir2','$comm2',NOW())";
  $result = mysql_query($sql, $dbDIR);
  $sql = "REPLACE INTO Direitos VALUES('1','$dir1',NOW())";
  $result = mysql_query($sql, $dbDIR);
  $sql = "REPLACE INTO Direitos VALUES('1','$dir2',NOW())";
  $result = mysql_query($sql, $dbDIR);
  //mysql_close($dbDIR);
  }
 */

function Inserir_Dir($db, $direito, $menu, $menuX)
{
     $sql = "CREATE TABLE ListaDireitos (
	Direito VARCHAR(64) NOT NULL,
	Descricao VARCHAR(255) NOT NULL,
	data DATETIME NOT NULL,
	menu VARCHAR(64) NOT NULL,
	PRIMARY KEY (Direito)
     )";
     $result = mysql_query($sql, $db);

     $sql = "CREATE TABLE Direitos (
	idUsuario INT(11) NOT NULL AUTO_INCREMENT,
	Direito VARCHAR(64) NOT NULL,
	Data DATETIME NOT NULL,
	PRIMARY KEY (`idUsuario`, `Direito`)
)
COMMENT='Controle Direitos dos Usuarios'
ENGINE=MyISAM";
     $result = mysql_query($sql, $db);

     $dir = "DIR_" . $menuX . "_" . $direito . "_LISTAR";
     $comm1 = "Listar Direitos da Tabela " . $direito;
     $comm2 = "Editar Direitos da Tabela " . $direito;
     $sql = "REPLACE INTO ListaDireitos VALUES('$dir','$comm1',NOW(),'$menu')";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     $sql = "REPLACE INTO Direitos VALUES('1','$dir',NOW())";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     $dir = "DIR_" . $menuX . "_" . $direito . "_EDITAR";
     $sql = "REPLACE INTO ListaDireitos VALUES('$dir','$comm2',NOW(),'$menu')";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     $sql = "REPLACE INTO Direitos VALUES('1','$dir',NOW())";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
}

function get_string_between($string, $start, $end)
{
     $string = " " . $string;
     $ini = strpos($string, $start);
     if($ini == 0)
     {
          return "";
     }
     $ini += strlen($start);
     $len = strpos($string, $end, $ini) - $ini;
     return substr($string, $ini, $len);
}

function getSize($campo)
{
     $size = get_string_between($campo, "(", ")");
     if($size != "")
     {
          $fim = strpos($campo, "(");
          $tipo = substr($campo, 0, $fim);
     }
     else
     {
          $size = 0;
          $tipo = $campo;
     }
     $ret = sprintf("%s;%s;", $tipo, $size);
     return $ret;
}

Function remover_acentos($palavra)
{
     $palavra = str_replace(" ", "_", $palavra);
     $palavra = str_replace(",", "_", $palavra);
     $palavra = str_replace("á", "a", $palavra);
     $palavra = str_replace("à", "a", $palavra);
     $palavra = str_replace("ã", "a", $palavra);
     $palavra = str_replace("â", "a", $palavra);
     $palavra = str_replace("é", "e", $palavra);
     $palavra = str_replace("ê", "e", $palavra);
     $palavra = str_replace("í", "i", $palavra);
     $palavra = str_replace("ó", "o", $palavra);
     $palavra = str_replace("ô", "o", $palavra);
     $palavra = str_replace("õ", "o", $palavra);
     $palavra = str_replace("ú", "u", $palavra);
     $palavra = str_replace("ü", "u", $palavra);
     $palavra = str_replace("ç", "c", $palavra);
     $palavra = str_replace("Á", "A", $palavra);
     $palavra = str_replace("À", "A", $palavra);
     $palavra = str_replace("Ã", "A", $palavra);
     $palavra = str_replace("Â", "A", $palavra);
     $palavra = str_replace("É", "E", $palavra);
     $palavra = str_replace("Ê", "E", $palavra);
     $palavra = str_replace("Í", "I", $palavra);
     $palavra = str_replace("Ó", "O", $palavra);
     $palavra = str_replace("Ô", "O", $palavra);
     $palavra = str_replace("Õ", "O", $palavra);
     $palavra = str_replace("Ú", "U", $palavra);
     $palavra = str_replace("Ü", "U", $palavra);
     $palavra = str_replace("Ç", "C", $palavra);
     $palavra = str_replace(".", "", $palavra);
     return strtoupper($palavra);
}

function remover_acentos1($palavra)
{
     //$palavra = ereg_replace("[^a-zA-Z0-9_]", "", strtr($palavra, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ ", "aaaaeeiooouucAAAAEEIOOOUUC_"));
     $palavra = ereg_replace("[^a-zA-Z0-9_]", "", strtr($palavra, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ ", "aaaaeeiooouucAAAAEEIOOOUUC_"));
     //$palavra = preg_replace("/[^a-zA-Z0-9_]/", "", strtr($palavra, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ", "aaaaeeiooouucAAAAEEIOOOUUC"));
     $palavra = str_replace(" ", "_", $palavra);
     $palavra = str_replace(",", "_", $palavra);

     return strtoupper($palavra);
}

function MontaDirMenu($db, $menu, $titulo='')
{
     $file = '';
     if($titulo == '')
     {
          $sql = "SELECT titulo FROM Menu_mount WHERE menu='$menu' ORDER BY titulo";
     }
     else
     {
          $sql = "SELECT titulo FROM Menu_mount WHERE menu='$menu' AND titulo LIKE '$titulo,%' ORDER BY titulo";
     }
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $file .= "<?php if(";
               $n = 0;
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[0], ",") == '')
                    {
                         if($n == 0)
                         {
                              $file .= sprintf("isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", remover_acentos($menu), remover_acentos($myrow[0]), remover_acentos($menu), remover_acentos($myrow[0]));
                         }
                         else
                         {
                              $file .= sprintf(" || isset(\$DIR_%s_%s_EDITAR) || isset(\$DIR_%s_%s_LISTAR)", remover_acentos($menu), remover_acentos($myrow[0]), remover_acentos($menu), remover_acentos($myrow[0]));
                         }
                    }
                    else
                    {
                         $ar = explode(",", $myrow[0]);
                         if($n == 0)
                         {
                              $file .= sprintf("isset(\$DIR_%s_%s_%s_EDITAR) || isset(\$DIR_%s_%s_%s_LISTAR)", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]), remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                         }
                         else
                         {
                              $file .= sprintf(" || isset(\$DIR_%s_%s_%s_EDITAR) || isset(\$DIR_%s_%s_%s_LISTAR)", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]), remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                         }
                    }
                    $n++;
               }
               $file .= ") {?>\n";
          }
     }
     return $file;
}

function MontaMenu($db, $diretorio, $idmenu)
{
     if($idmenu == 0)
     {
          $file = "<ul class='menu' id='menu'>\n";
     }
     else if($idmenu == 1 || $idmenu == 4)
     {
          $file = "<ul id='nav'>\n";
     }
     else if($idmenu == 2)
     {
          $file = "<ul>\n";
     }
     else if($idmenu == 3)
     {
          $file = "<ul id='potato'>\n";
     }

     $sql = "SELECT menu,titulo,url FROM Menu_mount ORDER BY menu,titulo";
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $menu = '';
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[0], 'button') != "")
                    {
                         $menu = '';
                         continue;
                    }
                    if($myrow[1] == '')
                    {
                         if(strstr($myrow[2], ";") == "")
                         {
                              $url = $myrow[2];
                              $js = "";
                         }
                         else
                         {
                              list($url, $js) = explode(";", $myrow[2]);
                              list($a, $name) = explode("=", $js);
                              $js = " onclick=\"return popup(this, '$name')\"";
                         }
                         $file .= sprintf("<li><a href='$url'$js>$myrow[0]</a></li>\n");
                         continue;
                    }
                    if(strstr($myrow[1], ",") != '')
                    {
                         continue;
                    }
                    if($menu != $myrow[0])
                    {
                         $menu = $myrow[0];
                         $file .= MontaDirMenu($db, $menu);
                         if($idmenu == 0)
                         {
                              $file .= sprintf("<li><a href='#' class='menulink'>$menu</a>\n");
                         }
                         else if($idmenu == 4)
                         {
                              $file .= sprintf("<li class='submenu'><a href='#' class='bullet'>$menu</a>\n");
                         }
                         else
                         {
                              $file .= sprintf("<li><a href='#'>$menu</a>\n");
                         }
                         $file .= MontaSub($db, $menu, $idmenu);
                         $file .= sprintf("</li>\n");
                         $file .= sprintf("<?php } ?>\n");
                    }
               }
          }
     }
     if($idmenu == 0)
     {
          $file .= sprintf("<li><a href='login.php?Logout=1' class='menulink'>Sair</a></li>\n");
     }
     else
     {
          $file .= sprintf("<li><a href='login.php?Logout=1'>Sair</a></li>\n");
     }
     $file .= "</ul>\n";

     $FILE = sprintf("%s/includes", $diretorio);
     if(!file_exists($FILE))
     {
          mkdir($FILE);
     }

     $FILE = sprintf("%s/includes/Menu.inc.php", $diretorio);
     $fPHP = fopen($FILE, "w");
     if(!$fPHP)
     {
          echo "<h1>Falha na Criacao do Arquivo '" . $FILE . "'</h1>";
          exit;
     }
     fprintf($fPHP, "%s", $file);
     fclose($fPHP);



     return;
}

function MontaSub($db, $menu, $idmenu, $titulo='')
{
     $file = sprintf("<ul>\n");
     if($titulo == '')
     {
          $class = '';
          $sql = "SELECT titulo,url FROM Menu_mount WHERE menu='$menu' ORDER BY titulo";
     }
     else
     {
          if($idmenu == 0)
          {
               $class = " class='topline'";
          }
          else
          {
               $class = '';
          }
          $sql = "SELECT titulo,url FROM Menu_mount WHERE menu='$menu' AND titulo LIKE '$titulo,%' ORDER BY titulo";
     }
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>)Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     else
     {
          if(mysql_num_rows($result) > 0)
          {
               $tit = '';
               while($myrow = mysql_fetch_row($result))
               {
                    if(strstr($myrow[0], ",") == '')
                    {
                         if(strstr($myrow[1], ";") == "")
                         {
                              $url = $myrow[1];
                              $js = "";
                         }
                         else
                         {
                              list($url, $js) = explode(";", $myrow[1]);
                              list($a, $name) = explode("=", $js);
                              $js = " onclick=\"return popup(this, '$name')\"";
                         }
                         $dirE = sprintf("\$DIR_%s_%s_EDITAR", remover_acentos($menu), remover_acentos($myrow[0]));
                         $dirE1 = sprintf("DIR_%s_%s_EDITAR", remover_acentos($menu), remover_acentos($myrow[0]));
                         $descricao = "Editar Dados da Tabela $myrow[0]";
                         Inserir_NewDir($db, $dirE1, $menu, $descricao);
                         $dirL = sprintf("\$DIR_%s_%s_LISTAR", remover_acentos($menu), remover_acentos($myrow[0]));
                         $dirL1 = sprintf("DIR_%s_%s_LISTAR", remover_acentos($menu), remover_acentos($myrow[0]));
                         $descricao = "Listar Dados da Tabela $myrow[0]";
                         Inserir_NewDir($db, $dirL1, $menu, $descricao);

                         $file .= sprintf("<?php if(isset($dirE) || isset($dirL)) { ?>\n");
                         $file .= sprintf("<li$class><a href='$url'$js>$myrow[0]</a></li>\n");
                         $file .= sprintf("<?php } ?>\n");
                         $class = '';
                    }
                    else
                    {
                         $ar = explode(",", $myrow[0]);
                         if($titulo != '')
                         {
                              if(strstr($myrow[1], ";") == "")
                              {
                                   $url = $myrow[1];
                                   $js = "";
                              }
                              else
                              {
                                   list($url, $js) = explode(";", $myrow[1]);
                                   list($a, $name) = explode("=", $js);
                                   $js = " onclick=\"return popup(this, '$name')\"";
                              }

                              $dirE = sprintf("\$DIR_%s_%s_%s_EDITAR", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                              $dirE1 = sprintf("DIR_%s_%s_%s_EDITAR", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                              $descricao = "Editar Dados da Tabela $ar[1]";
                              Inserir_NewDir($db, $dirE1, $menu, $descricao);
                              $dirL = sprintf("\$DIR_%s_%s_%s_LISTAR", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                              $dirL1 = sprintf("DIR_%s_%s_%s_LISTAR", remover_acentos($menu), remover_acentos($ar[0]), remover_acentos($ar[1]));
                              $descricao = "Listar Dados da Tabela $ar[1]";
                              Inserir_NewDir($db, $dirL1, $menu, $descricao);

                              $file .= sprintf("<?php if(isset($dirE) || isset($dirL)) { ?>\n");
                              $file .= sprintf("<li$class><a href='$url'$js>$ar[1]</a></li>\n");
                              $file .= sprintf("<?php } ?>\n");
                              $class = '';
                         }
                         else
                         {
                              //$ar = explode(",",$myrow[0]);
                              if($tit != $ar[0])
                              {
                                   $tit = $ar[0];
                                   $file .= MontaDirMenu($db, $menu, $ar[0]);
                                   if($idmenu == 4)
                                   {
                                        $file .= sprintf("<li class='submenu'><a href='#' class='bullet'>$ar[0]</a>\n");
                                   }
                                   else
                                   {
                                        $file .= sprintf("<li><a href='#' class='sub'>$ar[0]</a>\n");
                                   }
                                   $file .= MontaSub($db, $menu, $idmenu, $ar[0]);
                                   $file .= sprintf("</li>\n");
                                   $file .= sprintf("<?php } ?>\n");
                              }
                         }
                    }
               }
          }
     }
     $file .= sprintf("</ul>\n");
     return $file;
}

function Inserir_NewDir($db, $direito, $menu, $descricao)
{
     $sql = "CREATE TABLE ListaDireitos (
	Direito VARCHAR(64) NOT NULL,
	Descricao VARCHAR(255) NOT NULL,
	data DATETIME NOT NULL,
	menu VARCHAR(64) NOT NULL,
	PRIMARY KEY (Direito)
     )";
     $result = mysql_query($sql, $db);

     $sql = "CREATE TABLE Direitos (
	idUsuario INT(11) NOT NULL AUTO_INCREMENT,
	Direito VARCHAR(64) NOT NULL,
	Data DATETIME NOT NULL,
	PRIMARY KEY (`idUsuario`, `Direito`)
)
COMMENT='Controle Direitos dos Usuarios'
ENGINE=MyISAM";
     $result = mysql_query($sql, $db);

     $sql = "REPLACE INTO ListaDireitos VALUES('$direito','$descricao',NOW(),'$menu')";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
     $sql = "REPLACE INTO Direitos VALUES('1','$direito',NOW())";
     //printf("<p>$sql</p>");
     $result = mysql_query($sql, $db);
     if($result == 0)
     {
          printf("<h1>Falha: %s</h1>\n", mysql_error($db));
          printf("<h3>%s</h3>\n", $sql);
          exit;
     }
}

?>
